import React, { useState, useEffect } from 'react'
import { useParams, useLocation } from 'react-router-dom'
import { Card, message } from 'antd'
import { useAppSelector, useAppDispatch } from '@/store'
import { fetchConnections } from '@/store/slices/connectionSlice'
import { getScript, updateScript } from '@/store/slices/scriptSlice'
import SQLExecutor from '@/components/Execution/SQLExecutor'
import { Connection } from '@/types/connection'
import { Script } from '@/types/script'

const ScriptEditor: React.FC = () => {
  const { scriptId } = useParams<{ scriptId: string }>()
  const location = useLocation()
  const dispatch = useAppDispatch()
  
  const { connections } = useAppSelector(state => state.connection)
  const { scripts } = useAppSelector(state => state.script)
  
  // 状态管理
  const [script, setScript] = useState<Script | null>(null)
  const [sqlContent, setSqlContent] = useState('')
  const [selectedConnection, setSelectedConnection] = useState<Connection | null>(null)
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)

  // 初始化
  useEffect(() => {
    dispatch(fetchConnections())
  }, [dispatch])

  // 加载脚本
  useEffect(() => {
    if (scriptId) {
      // 从store中查找脚本
      const foundScript = scripts.find(s => s.id === scriptId)
      if (foundScript) {
        setScript(foundScript)
        setSqlContent(foundScript.content)
      } else {
        // 从API加载脚本
        dispatch(getScript(scriptId)).then((result: any) => {
          if (result.payload) {
            setScript(result.payload)
            setSqlContent(result.payload.content)
          }
        })
      }
    } else {
      // 新建脚本
      setSqlContent('')
      setScript(null)
    }
  }, [scriptId, scripts, dispatch])

  // 处理location state中的自动执行
  useEffect(() => {
    const state = location.state as any
    if (state?.autoExecute && state?.script) {
      setScript(state.script)
      setSqlContent(state.script.content)
    }
  }, [location.state])

  // 设置默认连接
  useEffect(() => {
    if (connections.length > 0 && !selectedConnection) {
      const activeConnection = connections.find(c => c.is_active) || connections[0]
      setSelectedConnection(activeConnection)
    }
  }, [connections, selectedConnection])

  // 处理SQL内容变化
  const handleSQLChange = (sql: string) => {
    setSqlContent(sql)
    setHasUnsavedChanges(script ? sql !== script.content : sql.trim() !== '')
  }

  // 处理连接变化
  const handleConnectionChange = (connection: Connection | null) => {
    setSelectedConnection(connection)
  }

  // 保存脚本
  const handleSaveScript = async () => {
    if (!sqlContent.trim()) {
      message.warning('请输入SQL内容')
      return
    }

    try {
      if (script) {
        await dispatch(updateScript({
          id: script.id,
          data: { content: sqlContent }
        }))
        setScript({ ...script, content: sqlContent })
        setHasUnsavedChanges(false)
        message.success('脚本已保存')
      } else {
        message.info('请先在脚本管理页面创建脚本')
      }
    } catch (error) {
      message.error('保存失败')
    }
  }

  return (
    <div style={{ 
      height: '100vh', 
      padding: '16px',
      background: '#f5f5f5',
    }}>
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span>{script ? script.name : '新建脚本'}</span>
            {hasUnsavedChanges && (
              <span style={{ color: '#faad14', fontSize: 12 }}>
                (未保存)
              </span>
            )}
          </div>
        }
        style={{ height: '100%' }}
        bodyStyle={{ 
          padding: 0, 
          height: 'calc(100% - 57px)',
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        <SQLExecutor
          initialSQL={sqlContent}
          initialConnection={selectedConnection}
          onSQLChange={handleSQLChange}
          onConnectionChange={handleConnectionChange}
          showHistory={true}
          showProgress={true}
          height={window.innerHeight - 150}
        />
      </Card>
    </div>
  )
}

export default ScriptEditor